<?php
namespace App\Http\Controllers\User;

use App\Models\Attendance;
use App\Models\Company;
use App\Models\Group;
use App\Models\Message;
use App\Models\RewardPunishDetailLog;
use App\Models\RewardPunishSetDetail;
use App\Models\ShenpiDetail;
use App\Models\ShenpiDetailLog;
use App\Models\User;
use App\Models\RewardPunishSet;
use App\Models\RewardPunishDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Input;
use App\Http\Controllers\User\UserBaseController;
use Illuminate\Support\Facades\Auth;


class RewardController extends UserBaseController
{

    public function __construct() {
        parent::__construct();
    }


    //我收到的奖惩
    public function getIndex(Request $request)
    {
        $year_param = $request->input('year', 0);
        $company = Company::where('id',$this->user->corpid)->first();
        if(!is_positive_int($year_param)){
            $year_param = getCurrentYear();
        }
        if(!in_array($year_param,explode(',',$company->years_array))){
            $year_param = $company->from_year;
        }
        $uid = $request->input('uid', 0);
        if(!is_positive_int($uid)){
            $user = Auth::user();
        }else{
            $user = User::find($uid);
        }

        $reward_set = RewardPunishSet::where('year_param',$year_param)->where('corpid',$this->user->corpid)->where('kind','1')->first();
        $rdetail = RewardPunishSetDetail::where('set_id',$reward_set->id)->lists('set_value','id')->toArray();
        $reward = RewardPunishDetail::where('year_param',$year_param)->where('corpid',$user->corpid)->where('to_user_id',$user->id)->where('is_effective','1')->where('kind','1')->get();
        $reward_score = 0;
        foreach ($reward as $r){
            if(isset($rdetail[$r->set_detail_id])){
                $sc = $rdetail[$r->set_detail_id];
            }else{
                $sc = 0;
            }
            $reward_score += $sc;
        }

        $punish_set = RewardPunishSet::where('year_param',$year_param)->where('corpid',$user->corpid)->where('kind','2')->first();
        $pdetail = RewardPunishSetDetail::where('set_id',$punish_set->id)->lists('set_value','id')->toArray();
        $punish = RewardPunishDetail::where('year_param',$year_param)->where('corpid',$user->corpid)->where('to_user_id',$user->id)->where('is_effective','1')->where('kind','2')->get();
        $punish_score = 0;
        foreach ($punish as $r){
            if(isset($pdetail[$r->set_detail_id])){
                $sc = $pdetail[$r->set_detail_id];
            }else{
                $sc = 0;
            }
            $punish_score += $sc;
        }

        //$reward_score = RewardPunishDetail::where('year_param',$year_param)->where('kind','1')->where('corpid',$this->corpid)->where('to_user_id',$this->user->id)->where('is_effective','1')->sum('score');
        //$punish_score = RewardPunishDetail::where('year_param',$year_param)->where('kind','2')->where('corpid',$this->corpid)->where('to_user_id',$this->user->id)->where('is_effective','1')->sum('score');
        //$reward = RewardPunishDetail::where('year_param',$year_param)->where('kind','1')->where('corpid',$this->corpid)->where('to_user_id',$this->user->id)->where('is_effective','1')->get();
        //$punish = RewardPunishDetail::where('year_param',$year_param)->where('kind','2')->where('corpid',$this->corpid)->where('to_user_id',$this->user->id)->where('is_effective','1')->get();
        $view = 'frontuser.rewards-punish';
        return view($view)
            ->with('user',$user)
            ->with('rescore',$reward_score)
            ->with('puscore',$punish_score)
            ->with('reward',$reward)
            ->with('pdetail',$pdetail)
            ->with('rdetail',$rdetail)
            ->with('year_param',$year_param)
            ->with('punish',$punish);
    }

    // 与我有关的奖惩&发起奖惩请求页面
    public function getReward(Request $request)
    {
        $id = $request->input('id',0);
        if($id == 1){
            $relate = RewardPunishDetail::where('corpid',$this->corpid)->where('kind','2')->where(function ($query) {
                $query->where('to_user_id',$this->user->id)->orWhere('from_user_id',$this->user->id);
            })->orderBy('created_at','desc')->get();
        }else{
            $id = 0;
            /*$relate = RewardPunishDetail::where('corpid',$this->corpid)->where('kind','1')->where(function ($query) {
                $query->where('to_user_id',$this->user->id)->orWhere('from_user_id',$this->user->id);
            })->orderBy('created_at','desc')->get();*/
            $relate = RewardPunishDetail::where('corpid',$this->corpid)->where('kind','1')->orderBy('created_at','desc')->get();//全员可见
        }
        //审核数量
        if($this->user->is_leader == 1){
            $count1 = RewardPunishDetail::where('corpid',$this->corpid)->where('is_effective','0')->where('current_group_id',$this->user->group_id)->count();
            $count2 = ShenpiDetail::where('corpid',$this->corpid)->where('status','0')->where('is_notify','0')->where('current_group_id',$this->user->group_id)->count();
        }else{
            $count1 = 0;
            $count2 = 0;
        }

        $count = $count1 + $count2;

        /*$relate = RewardPunishDetail::where('corpid',$this->corpid)->where(function ($query) {
            $query->where('kind','1')->orWhere('kind','2')->where('to_user_id',$this->user->id)->orWhere('from_user_id',$this->user->id);
        })->orderBy('created_at','desc')->get();*/

        $users = User::where('corpid',$this->corpid)->where('status','1')->where('id','!=',$this->user->id)->orderByRaw('CONVERT (kh_users.qw_name USING gbk)')->get();

        $view = 'frontuser.up-rewards';
        return view($view)
            ->with('id',$id)
            ->with('count',$count)
            ->with('user',$this->user)
            ->with('relate',$relate)
            ->with('users',$users);
    }


    // 与我有关的待办事项
    public function getShenpi(Request $request)
    {
        if($this->user->is_leader == 1){
            $count1 = RewardPunishDetail::where('corpid',$this->corpid)->where('is_effective','0')->where('current_group_id',$this->user->group_id)->count();
            $count2 = ShenpiDetail::where('corpid',$this->corpid)->where('status','0')->where('is_notify','0')->where('current_group_id',$this->user->group_id)->count();
        }else{
            $count1 = 0;
            $count2 = 0;
        }
        $count = $count1 + $count2;
        $relate = ShenpiDetail::where('corpid',$this->corpid)->where(function ($query) {
            $query->where('from_user_id',$this->user->id);
        })->orderBy('created_at','desc')->get();
        $users = User::where('corpid',$this->corpid)->where('status','1')->where('id','!=',$this->user->id)->get();
        $view = 'frontuser.up-rewards1';
        $kind_array = array('出差','事假','病假','年假','婚假','其他');
        return view($view)
            ->with('kind_array',$kind_array)
            ->with('count',$count)
            ->with('user',$this->user)
            ->with('relate',$relate)
            ->with('users',$users);
    }
    

    //发起奖励惩罚
    public function postAddReward(Request $request)
    {
        $result = array(
            'status'        => 'success',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );
        $reason = $request->input('reason','');
        $grade = $request->input('grade','');
        $kind = $request->input('kind','1');
        $year_param = date('Y');
        $month_param = date('Ym');
        $date_param = date('Ymd');
        //$score = $request->input('score',0);
        if(empty($grade)  || ($kind != '1' && $kind != '2')){
            $result['status'] = 'fail';
            $result['msg'] = '参数有误,等级，奖惩种类有误';
            return Response::json($result);
        }
        if(empty($reason)){
            $result['status'] = 'fail';
            $result['msg'] = '参数有误,奖惩原因不能为空';
            return Response::json($result);
        }
        $to_user_id = $request->input('uid',0);
        if($to_user_id <= 0){
            $result['status'] = 'fail';
            $result['msg'] = 'to_user_id无效';
            return Response::json($result);
        }
        $to_user = User::find($to_user_id);
        if($to_user->corpid != $this->corpid){
            $result['status'] = 'fail';
            $result['msg'] = '您没有权限评价该员工';
            return Response::json($result);
        }

        if($kind == 1){
            $reward_set = RewardPunishSet::where('year_param',$year_param)->where('corpid',$this->corpid)->where('kind','1')->first();
            $reward_set_detail = RewardPunishSetDetail::where('set_id',$reward_set->id)->lists('id','set_name')->toArray();
            //$set = unserialize($reward_set->detail);
            $score = $reward_set_detail[$grade];
            $set_detal_id = $reward_set_detail[$grade];
            $kname = '奖励';
        }else{
            $punish_set = RewardPunishSet::where('year_param',$year_param)->where('corpid',$this->corpid)->where('kind','2')->first();
            $punish_set_detail = RewardPunishSetDetail::where('set_id',$punish_set->id)->lists('id','set_name')->toArray();
            //$set = unserialize($punish_set->detail);
            $score = $punish_set_detail[$grade];
            $set_detal_id = $punish_set_detail[$grade];
            $kname = '惩罚';
        }
        $msg1 = $this->user->qw_name.'发起了对'.$to_user->qw_name.'的'.$kname.',等级为'.$grade;
        $msg = $this->user->qw_name.'发起了对'.$to_user->qw_name.'的'.$kname.',原因是'.trim($reason);
        $detail[] = $msg;


        $reward = new RewardPunishDetail();
        $reward->corpid = $this->corpid;
        $reward->kind = $kind;
        $reward->from_user_id = $this->user->id;
        $reward->to_user_id = $to_user_id;
        $reward->current_group_id = $to_user->group_id;
        $reward->reason = trim($reason);
        $reward->grade = $grade;
        $reward->score = 0;
        $reward->set_detail_id = $set_detal_id;
        $reward->detail = serialize($detail);
        $reward->year_param = $year_param;
        $reward->month_param = $month_param;
        $reward->date_param = $date_param;
        $reward->save();

        $log = new RewardPunishDetailLog();
        $log->rp_id = $reward->id;
        $log->operater_id = $this->user->id;
        $log->des = $msg;
        $log->save();

        $log1 = new RewardPunishDetailLog();
        $log1->rp_id = $reward->id;
        $log1->operater_id = $this->user->id;
        $log1->des = '等待审核';
        $log1->group_id = $to_user->group_id;
        $log1->method = 4;//下一步
        $log1->save();

        $message = new Message();
        $message->corpid = $this->corpid;
        $message->content = $msg1;
        $message->kind = $kind;
        if($kind=='1'){
            $scope = '';
        }else{
            $message->from_user_id = $this->user->id;
            $message->to_user_id = $to_user_id;
            $arr = array($this->user->id,$to_user_id);
            $scope = serialize($arr);
        }
        $message->scope = $scope;
        $message->save();


        $result['msg'] = '提交请求成功，等待批复';
        return Response::json($result);

    }


//检测是否有组长权限
    public function postCheckVerifyList(Request $request)
    {
        $response = array(
            'status'        => 'fail',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );
        if($this->user->is_leader != '1'){
            $response['msg'] = '您不是组长，暂时无法查看';
            return Response::json($response);
        }
        
        $response['status'] = 'success';
        return Response::json($response);

    }
    
    
    
    //组长审核奖励惩罚列表
    public function getVerifyList(Request $request)
    {
        if($this->user->is_leader != '1'){
            return '您不是组长，暂时无法查看';
        }
        $shenpicount = ShenpiDetail::where('corpid',$this->corpid)->where('status','0')->where('current_group_id',$this->user->group_id)->count();
        $rcount = RewardPunishDetail::where('corpid',$this->corpid)->where('is_effective','0')->where('current_group_id',$this->user->group_id)->where('kind','1')->count();
        $pcount = RewardPunishDetail::where('corpid',$this->corpid)->where('is_effective','0')->where('current_group_id',$this->user->group_id)->where('kind','2')->count();
        $reward = RewardPunishDetail::where('corpid',$this->corpid)->where('is_effective','0')->where('current_group_id',$this->user->group_id)->where('kind','1')->orderBy('created_at','desc')->get();
        $punish = RewardPunishDetail::where('corpid',$this->corpid)->where('is_effective','0')->where('current_group_id',$this->user->group_id)->where('kind','2')->orderBy('created_at','desc')->get();
        $reward_set = RewardPunishSet::where('corpid',$this->corpid)->where('kind','1')->first();
        $punish_set = RewardPunishSet::where('corpid',$this->corpid)->where('kind','2')->first();
        $reward_set = unserialize($reward_set->detail);
        foreach ($reward_set as $k=>$v){
            $setR[] = array(
                'title'=>$k,
                'value'=>$v
            );
        }
        $punish_set = unserialize($punish_set->detail);
        foreach ($punish_set as $k=>$v){
            $setP[] = array(
                'title'=>$k,
                'value'=>$v
            );
        }
        $setR = json_encode($setR);
        $setP = json_encode($setP);
        
        $view = 'frontuser.verify-reward';

        return view($view)
            ->with('shenpicount',$shenpicount)
            ->with('pcount',$pcount)
            ->with('rcount',$rcount)
            ->with('reward_set',$setR)
            ->with('punish_set',$setP)
            ->with('reward',$reward)
            ->with('punish',$punish);
    }

    //上级审核奖励或惩罚
    public function postVerifyReward(Request $request)
    {
        $response = array(
            'status'        => 'fail',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );
        if($this->user->is_leader != '1'){
            $response['msg'] = '您不是组长，暂时无法查看';
            return Response::json($response);
        }
        $rewardid = $request->input('rid',0);
        $grade = $request->input('grade','');
        $is_agree = $request->input('agree','1');
        $score = $request->input('level',0);
        $reason = $request->input('reason','');
        //dd($request->all());
        if($is_agree == 1){
            if( empty($grade)  || $rewardid<=0){
                $result['msg'] = '通过参数有误';
                return Response::json($result);
            }
        }else{
            if($rewardid<=0){
                $result['msg'] = '拒绝参数有误';
                return Response::json($result);
            }
        }

        $reward = RewardPunishDetail::find($rewardid);
        if(empty($reward)){
            $response['msg'] = '该记录不存在';
            return Response::json($response);
        }
        if($reward->current_group_id != $this->user->group_id){
            $response['msg'] = '您暂时无权审核该记录';
            return Response::json($response);
        }
        $up_group = Group::find($reward->current_group_id);
        if(empty($up_group)){
            $up_group_id = 0;
        }else{
            $up_group_id = $up_group->fid;
        }
        $detail = unserialize($reward->detail);
        if($is_agree != '1'){
            if(empty($reason)){
                $msg = $this->user->qw_name.'不同意该奖惩记录';
            }else{
                $msg = $this->user->qw_name.'不同意该奖惩记录,拒绝理由:'.$reason;
            }
        }else{
            $msg = $this->user->qw_name.'同意该奖惩记录，等级为'.$grade;
        }
        $detail[] = $msg;
        if($is_agree == '1'){
            if($reward->grade == $grade){
                $method = 1;//同意
            }else{
                $reward->grade = $grade;
                $method = 3;//修改等级
            }
            //$reward->score = $score;
        }else{
            $method = 2;
        }
        $reward->current_group_id = $up_group_id;
        $reward->detail = serialize($detail);
        if($up_group_id == '0'){
            $reward->is_effective = 1;
            $reward->effective_month = date('Ym',time());
            $detail[] = '奖惩生效';
            //生效时发送系统消息
            $message = new Message();
            $message->corpid = $this->corpid;
            $message->kind = $reward->kind;
            if($reward->kind=='1'){
                $scope = '';
                $kname = '奖励';
            }else{
                $kname = '惩罚';
                $arr = array($reward->from_user_id,$reward->to_user_id);
                $scope = serialize($arr);
            }
            $message->content = $reward->from_user_id.'发起的对'.$reward->to_user_id.'的'.$kname.'已生效';
            $message->scope = $scope;
            $message->save();

        }
        $reward->save();

        $delete_log = RewardPunishDetailLog::where('rp_id',$reward->id)->where('method',4)->delete();

        $log = new RewardPunishDetailLog();
        $log->rp_id = $reward->id;
        $log->operater_id = $this->user->id;
        $log->des = $msg;
        $log->group_id = $this->user->group_id;
        $log->method = $method;
        $log->save();

        if($up_group_id != '0'){
            $log1 = new RewardPunishDetailLog();
            $log1->rp_id = $reward->id;
            $log1->operater_id = $this->user->id;
            $log1->des = '等待审核';
            $log1->group_id = $up_group_id;
            $log1->method = 4;//下一步
            $log1->save();
        }else{
            $log1 = new RewardPunishDetailLog();
            $log1->rp_id = $reward->id;
            $log1->operater_id = $this->user->id;
            $log1->des = '奖惩生效';
            $log1->group_id = $up_group_id;
            $log1->method = $method;//下一步
            $log1->save();
        }


        $response['status'] = 'success';
        $response['msg'] = '审核奖惩成功';
        return Response::json($response);

    }


    //发起审批
    public function postAddShenpi(Request $request)
    {
        $result = array(
            'status'        => 'success',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );
        $des = $request->input('des','');
        $kind = $request->input('kind','1');
        $date = $request->input('date','');
        if(empty($date)){
            $result['status'] = 'fail';
            $result['msg'] = '参数有误,日期不能为空';
            return Response::json($result);
        }
        $timestamp = strtotime($date);
        $year_param = date('Y',$timestamp);
        $month_param = date('Ym',$timestamp);
        $date_param = date('Ymd',$timestamp);
        //dd($date,$timestamp,$request->all());

        //1-出差，2-事假，3,-病假，4-年假，5-婚假，6-其他
        $kind_array = array('出差','事假','病假','年假','婚假','其他');
        if(!in_array($kind,[1,2,3,4,5,6])){
            $result['status'] = 'fail';
            $result['msg'] = '参数有误,请选择类型';
            return Response::json($result);
        }
        if(empty($des)){
            $result['status'] = 'fail';
            $result['msg'] = '参数有误,描述不能为空';
            return Response::json($result);
        }
        $to_user_id = 0;

        $msg1 = $this->user->qw_name.'提出了'.$kind_array[$kind-1].'申请';
        $msg = $this->user->qw_name.'提出了'.$kind_array[$kind-1].'申请';
        $detail[] = $msg;

        if($this->user->is_leader == 1){
            $up_group = Group::find($this->user->group_id);
            if(empty($up_group)){
                $shenpi_group_id = $this->user->group_id;
            }else{
                if($up_group->fid == 0){
                    $shenpi_group_id = $up_group->id;
                }else{
                    $shenpi_group_id = $up_group->fid;
                }

            }
        }else{
            $shenpi_group_id = $this->user->group_id;
        }


        $reward = new ShenpiDetail();
        $reward->corpid = $this->corpid;
        $reward->kind = $kind;
        $reward->from_user_id = $this->user->id;
        $reward->to_user_id = $to_user_id;
        $reward->current_group_id = $shenpi_group_id;
        $reward->description = trim($des);
        $reward->detail = serialize($detail);
        $reward->year_param = $year_param;
        $reward->month_param = $month_param;
        $reward->date_param = $date_param;
        $reward->save();


        $log1 = new ShenpiDetailLog();
        $log1->rp_id = $reward->id;
        $log1->operater_id = $this->user->id;
        $log1->des = $msg;
        $log1->group_id = $this->user->group_id;
        $log1->save();


        $log2 = new ShenpiDetailLog();
        $log2->rp_id = $reward->id;
        $log2->operater_id = $this->user->id;
        $log2->des = '等待审核';
        $log2->group_id = $this->user->group_id;
        $log2->method = 4;//下一步
        $log2->save();

        $result['msg'] = '提交成功，等待审核';
        return Response::json($result);

    }



    //组长审核奖励惩罚列表
    public function getVerifyShenpi(Request $request)
    {
        if($this->user->is_leader != '1'){
            return '您不是组长，暂时无法查看';
        }
        $shenpicount = ShenpiDetail::where('corpid',$this->corpid)->where('status','0')->where('is_notify',0)->where('current_group_id',$this->user->group_id)->count();
        $rcount = RewardPunishDetail::where('corpid',$this->corpid)->where('is_effective','0')->where('current_group_id',$this->user->group_id)->where('kind','1')->count();
        $pcount = RewardPunishDetail::where('corpid',$this->corpid)->where('is_effective','0')->where('current_group_id',$this->user->group_id)->where('kind','2')->count();
        $shenpi = ShenpiDetail::where('corpid',$this->corpid)->where('current_group_id',$this->user->group_id)->where('is_notify',0)->orderBy('status','asc')->orderBy('created_at','desc')->get();


        $kind_array = array('出差','事假','病假','年假','婚假','其他');

        $view = 'frontuser.verify-reward1';

        return view($view)
            ->with('shenpicount',$shenpicount)
            ->with('kind_array',$kind_array)
            ->with('pcount',$pcount)
            ->with('rcount',$rcount)
            ->with('shenpi',$shenpi);
    }

    //上级审核奖励或惩罚
    public function postVerifyShenpi(Request $request)
    {
        $response = array(
            'status'        => 'fail',
            'msg'           => 'ok',
            'data'          => '',
            'redirectUrl'   => ''
        );
        if($this->user->is_leader != '1'){
            $response['msg'] = '您不是组长，暂时无法查看';
            return Response::json($response);
        }
        $rewardid = $request->input('rid',0);
        $is_agree = $request->input('agree','1');
        //dd($request->all());
        if($is_agree == 1){
            if($rewardid<=0){
                $result['msg'] = '通过参数有误';
                return Response::json($result);
            }
        }else{
            if($rewardid<=0){
                $result['msg'] = '拒绝参数有误';
                return Response::json($result);
            }
        }

        $reward = ShenpiDetail::find($rewardid);
        if(empty($reward)){
            $response['msg'] = '该记录不存在';
            return Response::json($response);
        }
        if($reward->current_group_id != $this->user->group_id){
            $response['msg'] = '您暂时无权审核该记录';
            return Response::json($response);
        }
        $up_group_id = 0;
        $detail = unserialize($reward->detail);
        if($is_agree != '1'){
            if(empty($reason)){
                $msg = $this->user->qw_name.'不同意该申请';
            }else{
                $msg = $this->user->qw_name.'不同意该申请';
            }
        }else{
            $msg = $this->user->qw_name.'同意该申请';
        }
        $detail[] = $msg;
        if($is_agree == '1'){
            $method = 1;//同意
            $reward->status = 1;

            $time = strtotime($reward->date_param);
            $Attendance=Attendance::firstOrCreate(['time'=>$time,'corpid'=>$this->corpid,'user_id'=>$reward->from_user_id]);
            $data['year_param'] = date('Y',$time);
            $data['month_param'] = date('Ym',$time);
            $data['date_param'] = date('Ymd',$time);
            $Attendance->update($data);
            if($reward->kind == 1){
                $Attendance->chuchai = 1;
            }elseif ($reward->kind == 2){
                $Attendance->business = 1;
            }elseif ($reward->kind == 3){
                $Attendance->sick = 1;
            }
            elseif ($reward->kind == 4){
                $Attendance->public = 1;//年假
            }elseif ($reward->kind == 5){
                $Attendance->public = 2;//婚假
            }
            elseif ($reward->kind == 6){
                $Attendance->qita = 1;
            }
            $Attendance->save();
        }else{
            $method = 2;
            $reward->status = 2;
        }
        //$reward->current_group_id = $reward->current_group_id;
        $reward->detail = serialize($detail);
        if($up_group_id == '0'){
            $reward->effective_month = date('Ym',time());
            $detail[] = '申请生效';
        }
        $reward->save();

        $log = new ShenpiDetailLog();
        $log->rp_id = $reward->id;
        $log->operater_id = $this->user->id;
        $log->des = $msg;
        $log->group_id = $this->user->group_id;
        $log->method = $method;
        $log->save();

        $delete_log = ShenpiDetailLog::where('rp_id',$reward->id)->where('method',4)->delete();


        $response['status'] = 'success';
        $response['msg'] = '审核成功';
        return Response::json($response);

    }




}


